# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class FujianZfxxgkPolicy(BaseTaxPolicySpider):
    name = 'fujian_zhangzhou_zfxxgk_policy'

    province = '福建省'
    city = '漳州市'
    # county = ''
    park = ''
    page_size = int(26 * 1.5)

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 407, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                # "DOWNLOADER_MIDDLEWARES": {
                #     "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                #     **downloader_middlewares
                # }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url in [
            ["漳州市人民政府", "", "https://www.zhangzhou.gov.cn/cms/html/zzsrmzf/zcwjkws/index.html"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self._parser_dataproxy_html,
                                 meta={"item": item})

    def _parser_dataproxy_html(self, response):
        meta = response.meta

        siteId = response.xpath("//*[@id='siteId']/@value").get()

        params = {
            "siteId": siteId,
            "requestType": "getInfo",
            "page": "1",
            "pageSize": "50",
            "mainDirectoryId": "",
            "mark": "",
            "topical": "",
            "topicalSecond": "",
            "infoYear": "",
            "abolish": "",
            "fileType": "",
            "serviceObject": "",
            "special": "",
            "keyWord": "",
            "beginDate": "",
            "endDate": ""
        }
        url = response.urljoin('/cms/infopublic/api/api.jsp') + '?'
        temp_url = url + urllib.parse.urlencode(params)
        meta.update({
            "params": params,
            "siteId": siteId,
            "url": url
        })
        print(params)
        yield self.Request(
            temp_url,
            callback=self.parse_list,
            dont_filter=True,
            meta=meta
        )

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        meta = response.meta
        siteId = meta['siteId']
        url_list = response.json()['data']['data']
        for elem in url_list:
            item = Item()
            # item['source_url'] = elem['chnldocurl']
            item['source_url'] = response.urljoin(f'/cms/infopublic/publicInfo.shtml?id={elem["id"]}&siteId={siteId}')
            item['publish_date'] = elem['created'].split(" ")[0] or elem['issueTime'].split(" ")[0]
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        page = meta.get('page', 1)
        if meta.get("is_next") is False:
            return
        total_count = int(response.json()['data']['total'])
        total_page = math.ceil(total_count / 50)
        print(meta['params'], page, "total_page", total_page)
        meta['is_next'] = False
        for page in list(range(2, total_page + 1)):
            params = meta['params']
            url = meta['url']
            params['page'] = page
            temp_url = url + urllib.parse.urlencode(params)
            self.logger.info(f"{total_page} 开始爬取 第 {page} 页 data: {params['siteId']}")
            yield self.Request(
                temp_url,
                meta=meta,
                callback=self.parse_list,
                dont_filter=True
            )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = item['publish_date'] or response.xpath(
            """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
            "//*[@class='fbrq']/text()").get()
        if item['publish_date']:
            item['publish_date'] = item['publish_date'].split(" ")[0]
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl fujian_zhangzhou_zfxxgk_policy -a get_next=0".split())
